/*
 * Copyright (c) 2009 Frederic Daoud
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package ${basePackage}.service;

import static ${basePackage}.model.AppRole.*;

import java.util.Date;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import ${basePackage}.model.AppRole;
import ${basePackage}.model.AppUser;
import ${basePackage}.model.Person;
import ${basePackage}.repository.Dao;

@Service
public class InitService {

  @Resource
  private Dao dao;

  @PostConstruct
  public void init() {
    createInitialPerson();
    createInitialRolesAndUsers();
  }

  private void createInitialPerson() {
    String name = "Freddy";
    Person person = dao.findSingleByField(Person.class, "name", name);
    if (person == null) {
      person = new Person();
      person.setName(name);
      person.setBirthDate(new Date());
      dao.save(person);
    }
  }

  private void createInitialRolesAndUsers() {
    Long adminId = dao.save(new AppRole(ADMINISTRATOR));
    Long memberId = dao.save(new AppRole(MEMBER));

    AppRole administrator = dao.findById(AppRole.class, adminId);
    AppRole member = dao.findById(AppRole.class, memberId);

    AppUser user = new AppUser();
    user.setUsername("freddy");
    // TODO: hash password
    user.setPassword("nadia");
    user.setEnabled(true);
    user.getRoles().add(administrator);
    user.getRoles().add(member);
    dao.save(user);
  }
}
